# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2023-02-11
desc: 
sample: 
"""
from apitest.models import TestCase, TestApiResult
from apitest.utils.RequestUtil import RequestUtil
from application.celery import app


@app.task
def apiTask(**kwargs):
    pk = kwargs.get("id")
    testcase = TestCase.objects.get(id=pk)
    print(f"apiTask {testcase}")
    if testcase:
        api = RequestUtil()
        api_queryset = testcase.apis.all()
        if api_queryset.exists():
            api = RequestUtil()
        try:
            for apiinfo in api_queryset:
                if apiinfo.params_type == 1:
                    data = apiinfo.params
                    data_parmas = {}
                    if not data:
                        for item in data.split("&"):
                            kvs = item.split("=")
                            key = kvs[0]
                            value = kvs[1]
                            data_parmas[key] = value
                    api.send_request(apiinfo.get_method_display(), apiinfo.url,
                                     verification=apiinfo.verification, case_desc=apiinfo.description,
                                     extract=apiinfo.extract, headers=apiinfo.headers, data=data_parmas)
                else:
                    api.send_request(apiinfo.get_method_display(), apiinfo.url,
                                     verification=apiinfo.verification, case_desc=apiinfo.description,
                                     extract=apiinfo.extract, headers=apiinfo.headers, json=apiinfo.jsonbody)

                print(api.get_result())
                result_dic = api.get_result()
                resultModel = TestApiResult()
                resultModel.project_belong = apiinfo.project_belong
                resultModel.module_belong = apiinfo.module_belong
                resultModel.api_belong = apiinfo
                resultModel.took_time = result_dic['took_time']
                resultModel.result = result_dic['response'][:100]
                resultModel.verification = result_dic['check_result']
                resultModel.case_belong = testcase
                resultModel.save()
        except:
            print('测试错误')

